package com.sinaapp.gavinzhang.lockTest;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by gavin on 15-8-30.
 */
public class LockTest {
    public static void main(String[] args)
    {
        final Lock lock = new ReentrantLock();
        final Condition condition = lock.newCondition();

        Thread t1 = new Thread(new Runnable() {
            public void run() {
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName()+"获得了锁，但是需要条件来启动");
                    condition.await();
                    System.out.println(Thread.currentThread().getName()+"得到信号，做你想做的事");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println(Thread.currentThread().getName()+"该结束了");
                    lock.unlock();
                }
            }
        },"consumer");
        t1.start();

        Thread t2 = new Thread(new Runnable() {
            public void run() {
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "获得了锁，我睡一会给信号");
                    Thread.sleep(1000);
                    condition.signalAll();
                    System.out.println(Thread.currentThread().getName() + "已经发送信号了");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println(Thread.currentThread().getName()+"该结束了");
                    lock.unlock();
                }
            }
        },"producer");
        t2.start();
    }
}
